﻿using System;
using System.Net;

namespace InfiniTec.Threading
{
	class UrlResourceConstraint: IResourceConstraint, IEquatable<UrlResourceConstraint>
	{
		private readonly Uri _Url;

		public UrlResourceConstraint(Uri url)
		{
			_Url = url;
		}

		public Uri Url { get { return _Url; } }


		public bool Equals(UrlResourceConstraint obj)
		{
			if (ReferenceEquals(null, obj)) return false;
			if (ReferenceEquals(this, obj)) return true;
			return Equals(obj._Url, _Url);
		}

		public override bool Equals(object obj)
		{
			if (ReferenceEquals(null, obj)) return false;
			if (ReferenceEquals(this, obj)) return true;
			if (obj.GetType() != typeof (UrlResourceConstraint)) return false;
			return Equals((UrlResourceConstraint) obj);
		}

		public override int GetHashCode()
		{
			return (_Url != null ? _Url.GetHashCode() : 0);
		}

		public static bool operator ==(UrlResourceConstraint left, UrlResourceConstraint right)
		{
			return Equals(left, right);
		}

		public static bool operator !=(UrlResourceConstraint left, UrlResourceConstraint right)
		{
			return !Equals(left, right);
		}

		public bool Equals(IResourceConstraint other)
		{
			return Equals(other as UrlResourceConstraint);
		}

		public int AllowedParalellOperations { get { return ServicePointManager.FindServicePoint(Url).ConnectionLimit; } }
	}
}
